//
//  ViewController.swift
//  RecognizeTextInImage
//
//  Created by lixin on 2023/9/26.
//

import UIKit
import Vision

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    @IBOutlet weak var resLabel: UILabel!
    
    
    @IBAction func recognizeAssetsImage(_ sender: Any) {
        recognizeText(in: #imageLiteral(resourceName: "image_sample"))
    }
    
    // 按钮点击，打开相册
    @IBAction func selectImage(_ sender: UIButton) {
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        present(imagePickerController, animated: true, completion: nil)
    }
    
    @IBAction func takeAPicture(_ sender: Any) {
        print("相机")
        let vc = ScanAlertVC()
        vc.modalPresentationStyle = .custom
        vc.scanResultBlock = { result in
            self.resLabel.text = result
        }
        self.present(vc, animated: true, completion: nil)
    }
    
    
    // 选择图片完成后的回调
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        picker.dismiss(animated: true, completion: nil)
        
        // 获取选择的图片
        guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
            return
        }
        
        let resImage = selectedImage
        // 识别图片中的文本
        recognizeText(in: resImage)
    }
    


    
    func recognizeText(in image: UIImage) {
        // 将 UIImage 转换为 CGImage
        guard let cgImage = image.cgImage else { return }
        
        // 创建处理请求的处理器
        let handler = VNImageRequestHandler(cgImage: cgImage, options: [:])
        
        // 创建 VNRecognizeTextRequest
        let request = VNRecognizeTextRequest { (request, error) in
            if let error = error {
                print("Text recognition error: \(error)")
                return
            }
            
            // 处理识别结果
            guard let observations = request.results as? [VNRecognizedTextObservation] else { return }
            for observation in observations {
                // 获取识别到的文本
                guard let topCandidate = observation.topCandidates(1).first else { continue }
                print("Recognized text: \(topCandidate.string)")
                self.resLabel.text = topCandidate.string
            }
        }
        
        // 设置识别级别
        request.recognitionLevel = .accurate
        
        // 执行请求
        do {
            try handler.perform([request])
        } catch {
            print("Failed to perform text recognition: \(error)")
        }
    }
}


